async function searchGoods(keyword) {
    // 模拟接口调用
    await new Promise(resolve => setTimeout(resolve, 300));
    return [keyword + '商品1', keyword + '商品2'];
}


const hotKeys = ['iPhone', 'iPad', '华为', '小米'];



/**
 * 创建搜索处理器
 * @returns Function 搜索处理函数
 */
function createSearchManager() {
    let timer = null;
    let resultId = 0
    let currentId = 0
    return function (keyword) {

        // 1. 处理关键词为空的情况
        if (!keyword.trim()) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            console.log('重新搜索');
            return;
        }

        // 2. 立即匹配热词并输出
        const matchedKeys = hotKeys.filter(key =>
            key.toLowerCase().includes(keyword.toLowerCase())
        );
        if (matchedKeys.length > 0) {
            console.log(`猜你想搜：${matchedKeys.join(', ')}`);
        }

        // 3. 实现防抖，等待用户停止输入500ms后调用搜索接口
        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(async () => {
            try {
                if (currentId === resultId) {
                    resultId++
                    const results = await searchGoods(keyword);
                    currentId++
                    console.log(results);
                }
            } catch (error) {
                console.error('搜索出错:', error);
            } finally {
                timer = null;
            }
        }, 500);
    };
}

const searchManager = createSearchManager();